require(["./config"], () => {
    require(["jquery", "request", "template", "header", "footer"], ($, req, template, Header) => {
        class Cart{
            constructor() {
                this.userTel = null;
                this.cartData = null;
                this.goodsList = [];
                this.init();
            }
            init() {
                this.pageInit();
                this.commendInit();
                
            }
            // 页面渲染函数
            pageInit() {
                new Header();
                const _this = this;
                this.userTel = localStorage.getItem("currentUser");
                let hasCart = false;
                let hasUser = false;
                let hasGoods = false;
                let userIndex = null;
                let goodsIndex = null;
                this.cartData = JSON.parse(localStorage.getItem("cartData"));
                hasCart = this.cartData && this.cartData.cartList.length ? true : false;
                if (hasCart) {
                    this.cartData.cartList.forEach((item, index) => {
                        if (item.userTel === this.userTel) {
                            hasUser = true;
                            userIndex = index;
                        }
                    })
                }
                if (hasUser) {
                    hasGoods = this.cartData.cartList[userIndex].goodsList.length ? true : false;
                }
                // console.log(hasCart, hasUser, hasGoods);

                if (hasGoods) {
                    // 有商品数据，显示商品数据
                    $(".cart-content .cartListBox").css("display", "block");
                    $(".cart-content .emptyBox").css("display", "none");
                    this.goodsList = this.cartData.cartList[userIndex].goodsList;
                    const htmlStr = template("cartListTemplate", {data : this.goodsList});
                    $("#cartListTemplateBox").html(htmlStr);
                } else {
                    // 无商品数据，有用户数据
                    if (hasUser) {
                        if (this.userTel === "游客") {
                            // 显示空购物车，有登录按钮
                            $(".cart-content .cartListBox").css("display", "none");
                            $(".cart-content .emptyBox").css("display", "block").find(".buttonBox a").first().css("display", "block");
                        } else {
                            // 显示空购物车，无登录按钮
                            $(".cart-content .cartListBox").css("display", "none");
                            $(".cart-content .emptyBox").css("display", "block").find(".buttonBox a").first().css("display", "none");
                        }
                    } else {
                        // 无购物车数据，无用户数据
                        // 显示空购物车，有登录按钮
                        $(".cart-content .cartListBox").css("display", "none");
                        $(".cart-content .emptyBox").css("display", "block").find(".buttonBox a").first().css("display", "block");
                    }
                }

                this.allCheckBtnInit();
                this.allCountInit();
                this.allPriceInit();

                // 单项栏选择按钮事件
                $(".cart-content-body .checkBtn")
                .click(function () {
                    goodsIndex = $(this).parents(".cartList").index();
                    if (_this.goodsList[goodsIndex].checked) {
                        _this.goodsList[goodsIndex].checked = false;
                        $(this).removeClass("checked");
                    } else {
                        _this.goodsList[goodsIndex].checked = true;
                        $(this).addClass("checked");
                    }
                    _this.cartData.cartList[userIndex].goodsList = _this.goodsList;
                    localStorage.setItem("cartData", JSON.stringify(_this.cartData));
                    _this.allCheckBtnInit();
                    _this.allCountInit();
                    _this.allPriceInit();
                })

                // 单选栏减量按钮事件
                $(".cart-content-body .downBtn")
                .click(function () {
                    goodsIndex = $(this).parents(".cartList").index();
                    let num = _this.goodsList[goodsIndex].count;
                    num = num > 1 ? num - 1 : 1;
                    let totalPrice = num * _this.goodsList[goodsIndex].price;
                    $(this).siblings(".count").text(num);
                    $(this).parents(".cartList").find(".totalPriceBox i").text(totalPrice);
                    _this.goodsList[goodsIndex].count = num;
                    _this.cartData.cartList[userIndex].goodsList = _this.goodsList;
                    localStorage.setItem("cartData", JSON.stringify(_this.cartData));
                    _this.allCheckBtnInit();
                    _this.allCountInit();
                    _this.allPriceInit();
                })

                // 单项栏加量按钮事件
                $(".cart-content-body .upBtn")
                .click(function () {
                    goodsIndex = $(this).parents(".cartList").index();
                    _this.goodsList[goodsIndex].count++;
                    let totalPrice = _this.goodsList[goodsIndex].count * _this.goodsList[goodsIndex].price;
                    $(this).siblings(".count").text(_this.goodsList[goodsIndex].count);
                    $(this).parents(".cartList").find(".totalPriceBox i").text(totalPrice);
                    _this.cartData.cartList[userIndex].goodsList = _this.goodsList;
                    localStorage.setItem("cartData", JSON.stringify(_this.cartData));
                    _this.allCheckBtnInit();
                    _this.allCountInit();
                    _this.allPriceInit();
                })

                // 单项栏删除按钮事件
                $(".cart-content-body .delBtn")
                .click(function () {
                    let goodsIndex = $(this).parents(".cartList").index();
                    // console.log(goodsIndex)
                    $(this).parents(".cartList").remove();
                    _this.goodsList.splice(goodsIndex, 1);
                    _this.cartData.cartList[userIndex].goodsList = _this.goodsList;
                    localStorage.setItem("cartData", JSON.stringify(_this.cartData));
                    _this.allCheckBtnInit();
                    _this.allCountInit();
                    _this.allPriceInit();
                    // console.log(_this.goodsList);
                    if (_this.goodsList.length === 0) {
                        // location.reload();
                        if (_this.userTel === "游客") {
                            // 显示空购物车，有登录按钮
                            $(".cart-content .cartListBox").css("display", "none");
                            $(".cart-content .emptyBox").css("display", "block").find(".buttonBox a").first().css("display", "block");
                        } else {
                            // 显示空购物车，无登录按钮
                            $(".cart-content .cartListBox").css("display", "none");
                            $(".cart-content .emptyBox").css("display", "block").find(".buttonBox a").first().css("display", "none");
                        }
                    }
                })

                // 汇总栏check按钮点击事件
                $(".cart-content-footer .checkBtn")
                .click(function () {
                    if ($(this).hasClass("checked")) {
                        $(".cartListBox").find(".checkBtn").removeClass("checked");
                        _this.goodsList = _this.goodsList.map((item) => {
                            item.checked = false;
                            return item;
                        })
                    } else {
                        $(".cartListBox").find(".checkBtn").addClass("checked");
                        _this.goodsList = _this.goodsList.map((item) => {
                            item.checked = true;
                            return item;
                        })
                    }
                    _this.cartData.cartList[userIndex].goodsList = _this.goodsList;
                    localStorage.setItem("cartData", JSON.stringify(_this.cartData));
                    _this.allCheckBtnInit();
                    _this.allCountInit();
                    _this.allPriceInit();
                })

            }


            // 汇总栏全选按钮状态初始化
            allCheckBtnInit() {
                this.goodsList.every((item) => {return item.checked}) ? $(".cart-content-footer .checkBtn").addClass("checked"): $(".cart-content-footer .checkBtn").removeClass("checked");
            }
            // 总数量初始化
            allCountInit() {
                let count = 0;
                this.goodsList.forEach((item) => {
                    item.checked ? count += item.count : null;
                })
                $(".cart-content-footer .allCountBox i").text(count);
            }
            // 总价格初始化
            allPriceInit() {
                let price = 0;
                this.goodsList.forEach((item) => {
                    item.checked ? price += item.count * item.price : null;
                })
                $(".cart-content-footer .allPriceBox i").text(price);
            }

            // 推荐页渲染
            commendInit() {
                return req.commendData()
                .then((res) => {
                    return new Promise((resolve) => {
                        if (res.code ===0) {
                            // console.log(res);
                            let list = res.data.list;
                            let goodsList = [];
                            // 从list中随机获取8各数据放入goodsList
                            for (let n = 0; n <8; n++) {
                                let length = list.length;
                                let index = Math.floor(Math.random() * length)
                                // console.log(list[index])
                                goodsList.push(list[index])
                                list.splice(index, 1)
                            }
                            // console.log(goodsList)
    
                            // 渲染推荐项
                            const htmlStr = template("commendTemplate", {data : goodsList})
                            // console.log(htmlStr)
                            $("#commendTemplateBox").html(htmlStr);
                            resolve();
                        }
                    })
                })
            }

        }
        new Cart();
    })
})